<!--
 * @Author: yuanweijiang
 * @Date: 2025-04-01 14:19:48
 * @LastEditors: XHM
-->
<template>
	<el-dialog
		title="创建服务"
		:width="dialogWidth"
		v-model="state.visible"
		:close-on-click-modal="false"
		draggable
		:destroy-on-close="true"
		@close="resetHandle"
	>
		<el-form ref="dialogFormRef" :label-width="activeIndex == 1 ? '140' : '100'" :model="state.queryForm" :rules="dataRules">
			<el-form-item label-width="100" label="创建类型" class="flex w-full items-center cursor-pointer gap-2" v-if="activeIndex == 3">
				<p class="tabList" v-for="(item, index) in serviceList" :key="item.value" @click="handleChoose(item, index)">{{ item.label }}</p>
			</el-form-item>

			<!-- 服务注册 -->
			<div class="w-full flex mb-3 justify-between" v-if="activeIndex == 1" style="height: 800px">
				<div class="register-left">
					<el-form-item label="服务名称" prop="serviceName">
						<el-input v-model="state.queryForm.serviceName" placeholder="请输入服务名称"></el-input>
					</el-form-item>
					<el-form-item label="所属目录" prop="serviceCatalogId">
						<el-select v-model="state.queryForm.serviceCatalogId" placeholder="请选择">
							<el-option v-for="item in serviceCatalogList" :key="item.name" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="服务描述" prop="describeStr">
						<el-input v-model="state.queryForm.describeStr" :rows="4" type="textarea" placeholder="请输入服务描述"></el-input>
					</el-form-item>
					<el-form-item label="服务路径" prop="serviceUrl">
						<el-input v-model="state.queryForm.serviceUrl" placeholder="请输入服务路径"></el-input>
					</el-form-item>

					<el-form-item label="源请求路径" prop="sourceServiceUrl">
						<el-input v-model="state.queryForm.sourceServiceUrl" placeholder="请输入资源名称"></el-input>
					</el-form-item>
					<el-form-item label="服务是否鉴权" prop="isAuthentication">
						<el-switch
							v-model="state.queryForm.isAuthentication"
							class="ml-2"
							:active-value="1"
							:inactive-value="2"
							style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
						/>
					</el-form-item>
					<el-form-item label="请求类型" prop="serviceRequestType" required>
						<el-radio-group v-model="state.queryForm.serviceRequestType">
							<el-radio :label="1">GET</el-radio>
							<el-radio :label="2">POST</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="是否为路径拼接参数" prop="montageFlag">
						<el-switch
							v-model="state.queryForm.montageFlag"
							class="ml-2"
							:active-value="1"
							:inactive-value="2"
							style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
						/>
					</el-form-item>
				</div>
				<div class="register-right">
					<el-form-item label="正常返回结果实例" prop="fileNameEn">
						<el-input disabled v-model="state.queryForm.successResult" :rows="5" type="textarea"></el-input>
					</el-form-item>
					<el-form-item label="异常返回结果实例" prop="fileNameEn">
						<el-input disabled v-model="state.queryForm.abnormalResult" :rows="5" type="textarea"></el-input>
					</el-form-item>
					<el-form-item label="请求参数格式" prop="contentType" required>
						<el-radio-group v-model="state.queryForm.contentType">
							<el-radio label="json">json</el-radio>
							<el-radio label="x-www-form-urlencoded">x-www-form-urlencoded</el-radio>
							<el-radio label="form-data">form-data</el-radio>
						</el-radio-group>
					</el-form-item>
					<!-- <el-form-item prop="port" label="请求超时时间">
						<div class="flex w-full justify-center"><el-input-number placeholder="请输入端口" v-model="state.queryForm.port" min="1" />ms</div>
					</el-form-item> -->

					<el-form-item class="relative" label="请求参数" prop="fileNameEn">
						<el-icon class="iconAdd cursor-pointer" @click="addDataList"><Plus /></el-icon>
					</el-form-item>
					<el-form-item>
						<el-table ref="tableDataRef" border :data="apidataList" style="width: 100%; height: 400px">
							<el-table-column prop="name" label="参数名称" align="center">
								<template #default="scope">
									<el-input v-model="scope.row.paramName"></el-input>
								</template>
							</el-table-column>
							<el-table-column prop="isMandatory" label="必填" align="center">
								<template #default="scope">
									<el-checkbox v-model.number="scope.row.isMandatory" size="large" />
								</template>
							</el-table-column>
							<el-table-column prop="describeStr" label="参数描述" align="center">
								<template #default="scope">
									<el-input v-model="scope.row.describeStr"></el-input>
								</template>
							</el-table-column>
							<el-table-column prop="setType" label="参数位置" align="center">
								<template #default="scope">
									<el-select v-model="scope.row.setType" placeholder="">
										<el-option v-for="item in typeList" :key="item.label" :label="item.label" :value="item.value" />
									</el-select>
								</template>
							</el-table-column>
							<el-table-column prop="paramType" label="参数类型" align="center">
								<template #default="scope">
									<el-select v-model="scope.row.paramType" placeholder="">
										<el-option v-for="item in paramTypeList" :key="item.label" :label="item.label" :value="item.value" />
									</el-select>
								</template>
							</el-table-column>
							<el-table-column prop="defaultValue" label="默认值" align="center">
								<template #default="scope">
									<el-input v-model="scope.row.defaultValue"></el-input>
								</template>
							</el-table-column>
							<el-table-column prop="name" label="操作" align="center">
								<template #default="scope">
									<el-icon class="iconAdd cursor-pointer" style="background: red" @click="minusHandle(scope.row.parameterId)"><Minus /></el-icon>
								</template>
							</el-table-column>
						</el-table>
					</el-form-item>
				</div>
			</div>
			<div class="flex gap-5 justify-between" v-if="activeIndex == 1">
				<el-button type="primary" class="dialogTrue" @click="returnHandle">上一步</el-button>
				<div>
					<el-button type="info" class="dialogTrue" @click="resetHandle">取消</el-button>
					<el-button type="primary" class="dialogTrue" @click="apiSave">保存</el-button>
				</div>
			</div>

			<!-- 数据表创建 -->
			<div class="w-full flex mb-3 justify-between" v-show="activeIndex == 0" style="height: 800px">
				<div class="register-left">
					<el-form-item label="服务名称" prop="serviceName">
						<el-input v-model="state.queryForm.serviceName" placeholder="请输入服务名称"></el-input>
					</el-form-item>
					<el-form-item label="所属目录" prop="serviceCatalogId">
						<el-select v-model="state.queryForm.serviceCatalogId" placeholder="请选择">
							<el-option v-for="item in serviceCatalogList" :key="item.name" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="服务描述" prop="describeStr">
						<el-input v-model="state.queryForm.describeStr" :rows="4" type="textarea" placeholder="请输入服务描述"></el-input>
					</el-form-item>
					<el-form-item label="服务路径" prop="serviceUrl">
						<el-input v-model="state.queryForm.serviceUrl" placeholder="请输入服务路径"></el-input>
					</el-form-item>
					<el-form-item label="请求类型" prop="serviceRequestType">
						<el-radio-group v-model="state.queryForm.serviceRequestType">
							<el-radio :label="1">GET</el-radio>
							<el-radio :label="2">POST</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="服务是否鉴权" prop="isAuthentication">
						<el-switch
							v-model="state.queryForm.isAuthentication"
							class="ml-2"
							:active-value="1"
							:inactive-value="2"
							style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
						/>
					</el-form-item>
					<el-form-item label="设置分页参数" prop="serviceResponseType">
						<el-checkbox :true-label="1" :false-label="0" v-model="state.queryForm.isPage" size="large" />
					</el-form-item>
					<el-table ref="tablePageRef" border v-if="state.queryForm.isPage == 1" :data="pageList" style="width: 100%; height: 140px">
						<el-table-column prop="name" show-overflow-tooltip label="参数名称" align="center"> </el-table-column>
						<el-table-column prop="ms" label="参数描述" align="center"> </el-table-column>
						<el-table-column prop="defaultStr" show-overflow-tooltip label="默认值" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.defaultStr"></el-input>
							</template>
						</el-table-column>
					</el-table>
					<!-- <el-form-item label="返回类型" prop="fileNameCh">
						<el-select v-model="state.queryForm.dbType" placeholder="请选择">
							<el-option v-for="item in []" :key="item.label" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item> -->
				</div>
				<div class="register-right flex flex-wrap">
					<div class="flex flex-col gap-2 mr-4" style="width: 48%; height: 360px">
						<p class="font-black" style="color: #000">数据源选择</p>
						<el-input v-model="sqlForm.name" placeholder="请输入数据源名称查询">
							<template #prepend>
								<el-button :icon="Search" @click="handlesqlList" />
							</template>
						</el-input>
						<el-select clearable v-model="sqlForm.dbType" placeholder="请选择" @change="handlesqlList">
							<el-option v-for="item in dataList" :key="item.label" :label="item.label" :value="item.value" />
						</el-select>
						<el-table
							highlight-current-row
							@row-click="handleCurrentChange"
							ref="tableRef"
							border
							:data="sqldataList"
							style="width: 100%; height: 80%"
						>
							<el-table-column prop="name" show-overflow-tooltip label="数据源名称" align="center"> </el-table-column>
							<el-table-column prop="dbType" label="类型" align="center"> </el-table-column>
							<el-table-column prop="description" show-overflow-tooltip label="数据源说明" align="center"> </el-table-column>
						</el-table>
					</div>
					<div class="flex flex-col gap-2" style="width: 48%; height: 360px">
						<p class="font-black" style="color: #000">数据表</p>
						<el-input v-model="tableValue" @change="searchTable" placeholder="请输入数据表名查询">
							<template #prepend>
								<el-button :icon="Search" @click="searchTable" />
							</template>
						</el-input>
						<el-table
							highlight-current-row
							@row-click="handleTableChange"
							ref="tableWatchRef"
							border
							:data="tableNameList"
							style="width: 100%; height: 80%"
						>
							<el-table-column prop="tableName" label="数据表名" align="center"> </el-table-column>
						</el-table>
					</div>
					<div class="w-full flex flex-col gap-2">
						<p class="font-black flex items-center" style="color: #000">
							<span class="mr-3">字段选择</span>
							<el-checkbox v-model="apiCheckFlag" @change="allApi" label="请求参数" size="large" />
							<el-checkbox v-model="isMandatoryFlag" @change="allIsMandatory" label="返回参数" size="large" />
						</p>
						<el-table ref="tableWordRef" border :data="sqlcolumnList" style="width: 100%; height: 360px">
							<el-table-column prop="paramName" label="字段名称" align="center"> </el-table-column>
							<el-table-column prop="paramType" show-overflow-tooltip label="字段类型" align="center"> </el-table-column>
							<el-table-column prop="describeStr" show-overflow-tooltip label="字段描述" align="center"> </el-table-column>
							<el-table-column prop="name" label="请求参数" align="center">
								<template #default="scope">
									<el-checkbox v-model.number="scope.row.apiCheck" size="large" @change="handleCheck(scope.row)" />
								</template>
							</el-table-column>
							<el-table-column prop="operate" label="操作符" align="center">
								<template #default="scope">
									<el-select :disabled="!scope.row.apiCheck" v-model="scope.row.operate" placeholder="">
										<el-option v-for="item in sqlList" :key="item.label" :label="item.label" :value="item.value" />
									</el-select>
								</template>
							</el-table-column>
							<el-table-column prop="defaultValue" label="默认值" align="center">
								<template #default="scope">
									<el-input :disabled="!scope.row.apiCheck" v-model="scope.row.defaultValue"></el-input>
								</template>
							</el-table-column>
							<el-table-column prop="name" label="返回参数" align="center">
								<template #default="scope">
									<el-checkbox v-model.number="scope.row.isMandatory" @change="handleIsMandatory(scope.row)" size="large" />
								</template>
							</el-table-column>
						</el-table>
					</div>
				</div>
			</div>
			<div class="flex gap-5 justify-between" v-if="activeIndex == 0">
				<el-button type="primary" class="dialogTrue" @click="returnHandle">上一步</el-button>
				<div>
					<el-button type="info" class="dialogTrue" @click="resetHandle">取消</el-button>
					<el-button type="primary" class="dialogTrue" @click="nextHandle">下一步</el-button>
				</div>
			</div>

			<!-- SQL编辑器 -->
			<div class="w-full flex mb-3 justify-between" v-if="activeIndex == 4">
				<div class="flex flex-col gap-4" style="width: 49%">
					<p class="font-black" style="color: #000">SQL编辑器</p>
					<div class="flex justify-between">
						<el-button type="info" class="dialogTrue" @click="resetSql">重置</el-button>
						<el-button type="primary" class="dialogTrue" @click="handleClickSql">执行</el-button>
					</div>
					<el-input v-model="state.queryForm.sqlText" :rows="14" type="textarea" placeholder=""></el-input>
				</div>
				<div class="gap-4 flex flex-col" style="width: 49%">
					<div>
						<p class="font-black mb-4" style="color: #000">请求参数</p>
						<el-input v-model="parameters" disabled :rows="4" type="textarea" placeholder=""></el-input>
					</div>
					<div>
						<p class="font-black mb-6" style="color: #000">正常调用结果</p>
						<el-input v-model="callesult" disabled :rows="9" type="textarea" placeholder=""></el-input>
					</div>
				</div>
			</div>
			<div class="flex gap-5 justify-between" v-if="activeIndex == 4">
				<el-button type="primary" class="dialogTrue" @click="handleReturn">上一步</el-button>
				<div>
					<el-button type="info" class="dialogTrue" @click="resetHandle">取消</el-button>
					<el-button type="primary" class="dialogTrue" @click="sqlSave">保存</el-button>
				</div>
			</div>
		</el-form>
	</el-dialog>
</template>

<script setup lang="ts" name="addLayerDialog">
import { useMessage } from '/@/hooks/message';
import { useUserInfo } from '/@/stores/userInfo';
import {
	getServiceCatalogTree,
	getList,
	tableList,
	executeQuery,
	columnList,
	addServiceManagement,
	updateServiceManagement,
} from '/@/api/datasource';
import { Search } from '@element-plus/icons-vue';
import { useTable } from '/@/hooks/table';
import { useDict } from '/@/hooks/dict';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['addLayer']);
// 引入组件

// 定义变量内容
const dialogFormRef = ref();
const apiCheckFlag = ref(false);
const isMandatoryFlag = ref(false);
const sqlcolumnList = ref([]);
const parameters = ref('');
const tableWatchRef = ref('');
const callesult = ref('');
const defaultProps = ref({
	children: 'children',
	label: 'name',
});
const { typeList, paramTypeList, dataList, sqlList } = useDict('typeList', 'paramTypeList', 'dataList', 'sqlList');

const dialogWidth = ref(450);
// 定义需要的数据
const apidataList = ref([]);
const tableNameList = ref([]);
const state = reactive({
	visible: false,
	queryForm: {},
});
const sqldataList = ref([]);
const tableValue = ref('');
const sqlTableValue = ref('');
const activeIndex = ref(3);
const pageList = ref([
	{
		name: 'page',
		ms: '页索引',
		defaultStr: '1',
	},
	{
		name: 'limit',
		ms: '每页条数',
		defaultStr: '10',
	},
]);
// 表单校验规则
const dataRules = reactive({
	nameSpace: [{ required: true, message: '项目不能为空', trigger: 'blur' }],
	layerInfo: [{ required: true, message: '文件不能为空', trigger: 'blur' }],
	serviceRequestType: [{ required: true, message: '请求类型为空', trigger: 'blur' }],
	contentType: [{ required: true, message: '参数格式不能为空', trigger: 'blur' }],
});
const serviceCatalogList = ref([]);
const tableRef = ref();
const serviceList = ref([
	{
		label: '数据表创建',
		value: 1,
	},
	{
		label: '服务注册',
		value: 2,
	},
]);
const sqlForm = ref({});
// 打开弹窗
const openDialog = (val: any) => {
	const {
		visible = true,
		queryForm = {
			abnormalResult: JSON.stringify(
				{
					code: 1,
					msg: '',
					data: null,
				},
				null,
				2
			),
			successResult: JSON.stringify(
				{
					code: 0,
					msg: 'ok',
					data: '保存成功',
				},
				null,
				2
			),
		},
	} = val;
	gruopInit();
	if (queryForm.serviceId) {
		if (activeIndex.value === 1) {
			apidataList.value = queryForm.parameterList;
			apidataList.value?.forEach((item) => {
				item.setType = typeList.value[Number(item.setType) - 1].label;
				item.isMandatory === 1 ? (item.isMandatory = true) : (item.isMandatory = false);
			});
		} else {
			let tableRefId = sqldataList.value?.filter((item) => {
				return item.id === queryForm.dataSourceId;
			})[0];
			nextTick(() => {
				if (tableRefId) {
					tableRef.value.setCurrentRow(tableRefId);
				}
			});
			tableList(queryForm.dataSourceId).then((res) => {
				let { data } = res;
				tableNameList.value = data;
				let tableWatchRefName = tableNameList.value?.filter((item) => {
					return item.tableName === queryForm.tableName;
				})[0];
				tableWatchRef.value.setCurrentRow(tableWatchRefName);
			});

			columnList({ id: queryForm.dataSourceId, tableName: queryForm.tableName }).then((res) => {
				let { data } = res;
				sqlcolumnList.value = data?.map((item) => {
					return {
						paramName: item.columnName,
						paramType: item.dataType,
						describeStr: item.columnComment,
					};
				});
				queryForm.parameterList?.forEach((item) => {
					sqlcolumnList.value?.forEach((res) => {
						if (item.paramName == res.paramName) {
							const { parameterId, serviceId, operate, defaultValue } = item;
							res.apiCheck = true;
							item.responseParam == 0 ? (res.isMandatory = false) : (res.isMandatory = true);
							res.parameterId = parameterId;
							res.serviceId = serviceId;
							res.operate = operate;
							res.defaultValue = defaultValue;
						}
					});
				});
				// queryForm.sqlText
				const match = queryForm.sqlText.match(/SELECT\s+(.*?)\s+FROM/i);
				// 提取结果
				const selectedFields = match ? match[1].trim().split(',') : null;
				sqlcolumnList.value?.forEach((item) => {
					if (selectedFields?.includes(item.paramName)) {
						item.isMandatory = true;
					} else {
						item.isMandatory = false;
					}
				});
			});
		}
	}

	Object.assign(state, { visible, queryForm });
};
function returnHandle() {
	activeIndex.value = 3;
	dialogWidth.value = 450;
}
function allApi() {
	sqlcolumnList.value.forEach((item) => {
		item.apiCheck = apiCheckFlag.value;
		if (item.apiCheck) {
			item.operate = '=';
		} else {
			item.operate = null;
		}
	});
}
function allIsMandatory() {
	sqlcolumnList.value.forEach((item) => {
		item.isMandatory = isMandatoryFlag.value;
	});
}
function searchTable() {
	if (!tableValue.value) {
		tableList(state.queryForm.dataSourceId).then((res) => {
			let { data } = res;
			tableNameList.value = data;
		});
		return;
	}
	tableNameList.value = tableNameList.value.filter((item) => item.tableName.includes(tableValue.value));
}
function addDataList() {
	apidataList.value.push({
		parameterId: new Date().getTime(),
	});
}
function handleCheck(val) {
	if (val.apiCheck) {
		val.operate = '=';
	} else {
		val.operate = null;
	}
	apiCheckFlag.value = sqlcolumnList.value.every((item) => item.apiCheck);
}

function handleIsMandatory(val) {
	isMandatoryFlag.value = sqlcolumnList.value.every((item) => item.isMandatory);
}
function resetSql() {
	state.queryForm.sqlText = '';
}
async function handleClickSql() {
	try {
		const res = await executeQuery({ id: state.queryForm.dataSourceId, sql: sqlTableValue.value });
		callesult.value = JSON.stringify(res, null, 2);
	} catch (error) {
		callesult.value = error.message;
	}
}
function minusHandle(id) {
	apidataList.value = apidataList.value.filter((item) => item.parameterId !== id);
}
async function sqlSave() {
	const valid = await dialogFormRef.value.validate().catch(() => {});
	if (!valid) return false;
	sqlcolumnList.value.forEach((item) => {
		item.isMandatory = item.isMandatory ? 1 : 0;
	});
	if (state.queryForm.isPage == 1) {
		sqlcolumnList.value.forEach((item) => {
			item.page = Number(pageList.value[0].defaultStr);
			item.limit = Number(pageList.value[1].defaultStr);
		});
	}

	state.queryForm.parameterList = sqlcolumnList.value.filter((item) => {
		return item.apiCheck;
	});

	// 删除多余参数
	const propertiesToDelete = ['apiUrl', 'approvalStatus', 'approveOpinion', 'releaseStatus', 'serviceStatus', 'createTime', 'updateTime', 'apiCheck'];

	for (const prop of propertiesToDelete) {
		delete state.queryForm[prop];
	}
	if (state.queryForm.parameterList) {
		for (let i = 0; i < state.queryForm.parameterList.length; i++) {
			delete state.queryForm.parameterList[i].apiCheck;
			delete state.queryForm.parameterList[i].limit;
			delete state.queryForm.parameterList[i].page;
		}
	}
	
	if (state.queryForm.serviceId) {
		await updateServiceManagement(state.queryForm);
		useMessage().success('修改成功');
		state.visible = false;
		emit('addLayer');
	} else {
		try {
			await addServiceManagement(state.queryForm);
			useMessage().success('保存成功');
			state.visible = false;
			emit('addLayer');
		} catch (error) {}
	}
}
handlesqlList();
function gruopInit() {
	serviceCatalogList.value = [];
	getServiceCatalogTree().then((res) => {
		let { data } = res;
		data.forEach((item) => {
			if (item.children) {
				serviceCatalogList.value.push(...item.children);
			}
		});
	});
	// tableList().then((res) => {
	// 	let { data } = res;
	// 	console.log(data);
	// });
}
function handlesqlList() {
	getList({
		current: 1,
		size: 1000,
		...sqlForm.value,
	}).then((res) => {
		let { data } = res;
		sqldataList.value = data.records;
	});
}
// 保存数据
const onSubmit = async () => {
	const valid = await dialogFormRef.value.validate().catch(() => {});
	if (!valid) return false;
};
function handleChoose(item, index) {
	activeIndex.value = index;
	state.queryForm.serviceType = item.value;
	dialogWidth.value = 1500;
}
//请求参数 1 返回参数2 都有3
function nextHandle() {
	activeIndex.value = 4;
	let apiArr: any[] = [];
	let isManArr: any[] = [];
	let dataQuery = [];
	let sjSqlList = [];
	sqlcolumnList.value?.forEach((item) => {
		if (item.apiCheck) {
			apiArr.push(`${item.paramName} ${item.operate} #{${item.paramName}}`);
			dataQuery.push(item);
			if (item.defaultValue) {
				sjSqlList.push(`${item.paramName} ${item.operate} ${item.defaultValue}`);
			}
		}
	});
	sqlcolumnList.value?.forEach((item) => {
		if (item.isMandatory) {
			isManArr.push(item.paramName);
		}
	});
	if (!apiArr.length > 0 && !isManArr.length > 0) {
		state.queryForm.sqlText = `SELECT FORM ${state.queryForm.tableName.value ? state.queryForm.tableName.value : ''}`;
		return;
	}
	state.queryForm.sqlText = `SELECT ${isManArr.join(',')} FROM ${state.queryForm.tableName} ${apiArr.length > 0 ? 'WHERE' : ''} ${apiArr.join(
		' AND '
	)}`;
	sqlTableValue.value = `SELECT ${isManArr.join(',')} FROM ${state.queryForm.tableName} ${sjSqlList.length > 0 ? 'WHERE' : ''} ${sjSqlList.join(
		' AND '
	)}`;
	// let testArr=dataQuery.filter
	const result = dataQuery
		.map((item) => {
			return item.paramName;
		})
		.reduce((obj, key) => {
			obj[key] = ''; // 设置每个 key 的值为空字符串
			return obj;
		}, {});
	parameters.value = JSON.stringify(result, null, 2);
}
function handleCurrentChange(row) {
	state.queryForm.dataSourceId = row.id;
	tableList(row.id).then((res) => {
		let { data } = res;
		tableNameList.value = data;
	});
}
function handleTableChange(row) {
	sqlcolumnList.value = [];
	state.queryForm.tableName = row.tableName;
	columnList({ id: state.queryForm.dataSourceId, tableName: row.tableName }).then((res) => {
		let { data } = res;
		sqlcolumnList.value = data.map((item) => {
			return {
				paramName: item.columnName,
				paramType: item.dataType,
				describeStr: item.columnComment,
			};
		});
	});
}

function handleReturn(params: type) {
	activeIndex.value = 0;
}
function resetHandle() {
	dialogFormRef.value.resetFields();
	state.visible = false;
	activeIndex.value = 3;
	dialogWidth.value = 450;
	apidataList.value = [];
	tableNameList.value = [];
	sqlcolumnList.value = [];
	apidataList.value = [];
}
async function apiSave() {
	const valid = await dialogFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	apidataList.value.forEach((item) => {
		item.isMandatory = item.isMandatory ? 1 : 0;
	});
	if (apidataList.value.length > 0) {
		let setTypeArr = apidataList.value.map((item) => {
			return item.setType ? item.setType : null;
		});
		if (setTypeArr.includes(null)) {
			useMessage().error('请选择参数位置');
			return;
		}
	}
	// 删除多余参数
	const propertiesToDelete = ['apiUrl', 'approvalStatus', 'approveOpinion', 'releaseStatus', 'serviceStatus', 'createTime', 'updateTime', 'apiCheck'];

	for (const prop of propertiesToDelete) {
		delete state.queryForm[prop];
	}
	
	if ( apidataList.value) {
		for (let i = 0; i <  apidataList.value.length; i++) {
			delete apidataList.value[i].parameterId;
		}
	}
	

	if (state.queryForm.serviceId) {
		apidataList.value.forEach((item) => {
			if (isNaN(Number(item.setType))) {
				typeList.value.forEach((res) => {
					if (res.label === item.setType) {
						item.setType = Number(res.value);
					}
				});
			}
		});
		state.queryForm.parameterList = apidataList.value;
	
		await updateServiceManagement(state.queryForm);
		useMessage().success('修改成功');
		state.visible = false;
		emit('addLayer');
	} else {
		try {
			state.queryForm.parameterList = apidataList.value;
			await addServiceManagement(state.queryForm);
			useMessage().success('保存成功');
			state.visible = false;
			emit('addLayer');
		} catch (error) {}
	}
}
// 暴露变量 只有暴漏出来的变量 父组件才能使用
defineExpose({
	openDialog,
	activeIndex,
	dialogWidth,
});
</script>

<style scoped lang="scss">
.dialog-footer {
	display: flex;
	justify-content: center;
}

.blue-card {
	margin: 5px;
	padding: 10px;
	border-radius: 8px;
	background: #eaf1ff;
}
.c {
	background: #eaf1ff;
	border-radius: 2px;
	color: #3156a5;
	padding: 0px 6px;
}

.tabList:hover {
	background: #3156a5;
	color: #fff;
}
.tabList {
	background: #eaf1ff;
	color: #3156a5;
	width: 49%;
	text-align: center;
	height: 40px;
	line-height: 40px;
	padding: 0px 6px;
}
.tabList:nth-child(1) {
	border-right: 1px solid;
}
.disabled-style {
	cursor: not-allowed !important; /* 鼠标样式表示不可点击 */
	/* 其他禁用样式 */
}
.register-left {
	width: 38%;
}
.register-right {
	width: 61%;
}
.iconAdd {
	background: #7ea5e0;
	color: #fff;
	font-size: 20px;
}
</style>
